import DialogStore from ".";
import { message } from 'antd';
import { each } from 'lodash';
import { Button } from 'antd';
import { observable, action, computed } from "mobx";
import { WeaForm } from 'comsMobx';
import API from '../../apis/cuspath';
import { READONLY, EDIT, REQUIRE } from '../../constants/path';
import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;

export default class FieldPropDialogStore extends DialogStore {
    @observable loading = true;
    @observable forms = [];
    @observable selectedForm = '';
    @observable form = new WeaForm();
    @observable selectedDetail = '';
    @observable parent;
    @observable readonly;
    @observable allCheckValues = {};
    @observable allCheckList = [{
        key: EDIT,
        showname: '是否编辑',
    }, {
        key: REQUIRE,
        showname: '是否必填',
    },
    {
        key: READONLY,
        showname: '是否只读',
    }];
    constructor(parent) {
        super();
        this.parent = parent;
        this.title = '字段属性设置';
        this.style = { width: 720, height: 520 };

        this.hasScroll = true;
    }

    @action save = () => {
        API.saveFormfieldprops({
            ...this.params,
            values: JSON.stringify(this.values)
        }).then(() => {
            message.success(getLabel('502231', '保存成功'));
            this.hide();
        });
    }
    @action open = (params) => {
        this.params = {};
        each(params, (value, key) => {
            if (value) {
                this.params[key] = value;
            }
        });
        this.visible = true;
        this.loading = true;
        this.getButtons();
        API.getFormfieldprops(this.params).then(this.setFormAndFields);
    }
    getButtons = () => {
        this.readonly = this.parent.readonly;
        if (!this.readonly) {
            this.buttons = [<Button key="cancel" type="primary" onClick={this.hide}>{getLabel(31129, '取消')}</Button>,
            <Button key="save" type="primary" onClick={this.save}>{getLabel(30986, '保存')}</Button>];
        } else {
            this.buttons = [<Button key="cancel" type="primary" onClick={this.hide}>{getLabel(31129, '取消')}</Button>];
        }
    }
    @action setFormAndFields = ({ forms }) => {
        this.loading = false;
        this.forms = forms.map(f => ({ ...f, formid: `${f.formid}` }));
        window.temp = this.form = new WeaForm();
        this.forms.forEach(form => {
            const { details, tables = [] } = form;
            this.form.add('', { key: form.formid });

            const allcheck = this.getAllCheckOptions();
            // this.allCheckList[form.formid] = allcheck;
            const field = this.form.$(form.formid);
            const mainFields = details.filter(d => !d.detailTable);
            mainFields.forEach(f => {
                const options = this.getOptions(f);
                const [defvalue] = options.filter(d => d.selected);
                field.add(f.combineType ? f.combineType : defvalue ? defvalue.key : '', { key: f.fieldid });
                const childField = field.$(f.fieldid);
                childField.set('label', '&nbsp;' + f.name);
                childField.set('options', options);
            });


            tables.forEach(table => {
                field.add('', { key: table.detailTable });
                const detailField = field.$(table.detailTable);
                const allcheck = this.getAllCheckOptions();
                // this.allCheckList[table.detailTable] = allcheck;
                const detialFields = details.filter(d => d.detailTable === table.detailTable);
                // detailField.add('1', { key: 'combineType' })
                detialFields.forEach(f => {
                    const fieldid = 'field' + f.fieldid;
                    const options = this.getOptions(f);
                    const [defvalue] = options.filter(d => d.selected);
                    detailField.add(f.combineType ? f.combineType : defvalue ? defvalue.key : '', { key: fieldid });
                    const childField = detailField.$(fieldid);
                    childField.set('label', '&nbsp;' + f.name);
                    childField.set('options', options);
                })
            })

        });
        this.selectedForm = this.forms.length > 0 ? this.forms[0].formid : '';
        this.selectedDetail = this.forms.length > 0 ? ((this.forms[0].tables || [])[0] || {}).detailTable || '' : '';
        this.setAllCheckValues();
    }
    @action changeSelectedForm = (selectedForm) => {
        this.selectedForm = selectedForm;
        this.selectedDetail = (((this.forms.filter(d => d.formid === selectedForm) || {})[0].tables || [])[0] || {}).detailTable || '';
        //this.selectedDetail = this.forms.filter(d=>d.formid ===selectedForm)[0].tables[0].detailTable
    }
    @action changeSelectedDetail = (selectedDetail) => {
        this.selectedDetail = selectedDetail;
    }
    get values() {
        const result = {};
        this.form.map(form => {
            const value = {};
            form.map(field => {
                value[field.key] = field.values();
            });
            result[form.key] = value;
        });
        return result;
    }
    getFields = (formid) => {
        return this.fields[formid] || [];
    }

    // READONLY,EDIT,REQUIRE
    getOptions = (field) => {
        if (!field) {
            filed = 'EDIT'
        }
        return [{
            key: EDIT,
            //showname: '                                   ',
            display: true,
            selected: 'EDIT' == field
        }, {
            key: REQUIRE,
            //showname: '必填',
            display: true,
            selected: 'REQUIRE' == field
        },
        {
            key: READONLY,
            //showname: '只读',
            display: true,
            selected: 'READONLY' == field
        }].filter(d => d.display);
    }

    getAllCheckOptions = (field) => {
        return [{
            key: EDIT,
            showname: '是否编辑',
            display: true,
            selected: 'EDIT' == field
        }, {
            key: REQUIRE,
            showname: '是否必填',
            display: true,
            selected: 'REQUIRE' == field
        },
        {
            key: READONLY,
            showname: '是否只读',
            display: true,
            selected: 'READONLY' == field
        }].filter(d => d.display);
    }

    allCheckChange = (value, mainKey, allcheckKey) => {
        this.form.map(form => {
            form.map(field => {
                if (allcheckKey) { // 主表
                    if (field.key === allcheckKey) {
                        field.map(detailField => {
                            detailField.set(value);
                        })
                    }
                } else {
                    if (!field.key.startsWith('edc_uf_table') && field.id.startsWith(mainKey)) {
                        field.set(value);
                    }
                }

            });
        });
        this.setAllCheckValues();
    }
    setAllCheckValues= ()=> {
        const result = {};
        const getValue = (fieldValues) => {
            const length = fieldValues.length;
            const isAllREADONLY = fieldValues.filter(d => d === 'READONLY').length === length;
            const isAllEDIT = fieldValues.filter(d => d === 'EDIT').length === length;
            const isAllREQUIRE = fieldValues.filter(d => d === 'REQUIRE').length === length;
            return isAllREADONLY ? 'READONLY' : isAllEDIT ? 'EDIT' : isAllREQUIRE ? 'REQUIRE' : undefined;
        }
        this.form.map(form => {
            const mainFieldValues = [];
            form.map(field => {
                if (field.key.startsWith('edc_uf_table')) { // 明细表
                    const fieldValues = field.map(d => d.values());
                    result[field.key] = getValue(fieldValues)
                } else {
                    mainFieldValues.push(field.values());
                }
            });
            if (mainFieldValues.length > 0) {
                result[`edc_uf_table${form.key}`] = getValue(mainFieldValues);
            }
        })
        this.allCheckValues = result;
    }
}